package encrypt

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"errors"
)

// 密钥（必须为16、24或32字节，分别对应AES-128、AES-192、AES-256）
const aesKey = "your-32bytes-aes-key-here-32bytes-long"

// AesEncrypt AES加密（CBC模式）
func AesEncrypt(plaintext string) (string, error) {
	// 创建加密块
	block, err := aes.NewCipher([]byte(aesKey))
	if err != nil {
		return "", err
	}

	// 填充明文
	plaintextBytes := []byte(plaintext)
	blockSize := block.BlockSize()
	plaintextBytes = pkcs7Padding(plaintextBytes, blockSize)

	// 创建CBC模式
	ciphertext := make([]byte, len(plaintextBytes))
	mode := cipher.NewCBCEncrypter(block, []byte(aesKey)[:blockSize])
	mode.CryptBlocks(ciphertext, plaintextBytes)

	// 编码为Base64
	return base64.StdEncoding.EncodeToString(ciphertext), nil
}

// AesDecrypt AES解密（CBC模式）
func AesDecrypt(ciphertext string) (string, error) {
	// 解码Base64
	ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return "", err
	}

	// 创建解密块
	block, err := aes.NewCipher([]byte(aesKey))
	if err != nil {
		return "", err
	}

	// 检查块大小
	blockSize := block.BlockSize()
	if len(ciphertextBytes)%blockSize != 0 {
		return "", errors.New("密文长度不是块大小的整数倍")
	}

	// 创建CBC模式
	mode := cipher.NewCBCDecrypter(block, []byte(aesKey)[:blockSize])
	plaintextBytes := make([]byte, len(ciphertextBytes))
	mode.CryptBlocks(plaintextBytes, ciphertextBytes)

	// 去除填充
	plaintextBytes = pkcs7UnPadding(plaintextBytes)

	return string(plaintextBytes), nil
}

// pkcs7Padding 实现PKCS#7填充
func pkcs7Padding(data []byte, blockSize int) []byte {
	padding := blockSize - len(data)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(data, padtext...)
}

// pkcs7UnPadding 移除PKCS#7填充
func pkcs7UnPadding(data []byte) []byte {
	length := len(data)
	if length == 0 {
		return nil
	}
	unpadding := int(data[length-1])
	if unpadding > length {
		return nil
	}
	return data[:(length - unpadding)]
}
